import 'dart:io';
import 'package:get/get.dart';
import 'package:yysk_app/net/api/common_api.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/pages/login/login_page.dart';
import 'package:yysk_app/pages/login/login_controller.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_log_off.dart';

import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/dialog_widget.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/utils/js_tool.dart';
import 'package:oktoast/oktoast.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:yysk_app/net/api/api_url.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hi_cache/flutter_hi_cache.dart';

enum DrawerType {
  aboutMe,
  modifyPassword,
  exchangePassword,
  bankListManager,
  realNameAuth, //未实名
  realNameInfo, //已实名
  clearMemoryCache,
}

class SettingController extends GetxController {
  final GlobalController globalController = Get.find();
  final type = DrawerType.aboutMe.obs;
  final enbled = false.obs; //登录密码按钮
  final changeExchangePswEnbled = false.obs; //修改交易密码按钮
  final avatarImg = ''.obs;
  final exchangePsw = ''.obs;

  final pwdErrorOne = ''.obs;
  final pwdErrorTwo = ''.obs;
  final exchangePwdError = ''.obs;

  final version = ''.obs;

  int? smsId;
  String? codes;
  String? pwd;
  String? againPwd;

  @override
  Future<void> onInit() async {
    super.onInit();
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    version.value = packageInfo.version;
  }

  void modifyPassword() {
    if (pwdErrorOne.value.isNotEmpty) {
      showToast(pwdErrorOne.value);
      return;
    }
    if (pwdErrorTwo.value.isNotEmpty) {
      showToast(pwdErrorTwo.value);
      return;
    }

    http.netFetch<dynamic>(
      ApiUrl.updateUserPassword,
      method: Method.post,
      params: {
        'smsId': smsId,
        'codes': codes,
        'onePwd': pwd,
        'twoPwd': againPwd,
      },
      success: (data) {
        showToast('修改成功！');
        Get.offAllNamed(LoginPage.path);
      },
    );
  }

  void exchangePasswordConfirm(BuildContext context) {
    if (exchangePwdError.value.isNotEmpty) {
      showToast(exchangePwdError.value);
      return;
    }

    http.netFetch<dynamic>(
      ApiUrl.updateExchangePassword,
      params: {'smsId': smsId, 'codes': codes, 'pwd': pwd},
      success: (data) {
        showToast('修改成功！');
        GlobalController globalController = Get.find();
        globalController.getUserInfo();
        Navigator.of(context).pop();
      },
    );
  }

  void changeType(DrawerType drawerType) {
    type.value = drawerType;
  }

  void changeValue(dynamic value, String type) {
    if (type == 'pwd') {
      pwd = value;
      _validatePasswordOne(value);
    }
    if (type == 'smsId') {
      smsId = value;
    }
    if (type == 'codes') {
      codes = value;
    }
    if (type == 'againPwd') {
      againPwd = value;
      _validatePasswordTwo(value);
    }
    checkModiy();
  }

  void _validatePasswordOne(String password) {
    // 定义正则表达式，要求密码同时包含数字、字母及特殊字符，且长度至少为8个字符
    RegExp regex = RegExp(r'^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,18}$');

    // 使用正则表达式进行匹配
    if (!regex.hasMatch(password)) {
      // 如果密码不符合规则，返回一个错误消息

      pwdErrorOne.value = '登录密码8-18位数，包含字母和数字，不支持特殊字符';
      return;
    }

    pwdErrorOne.value = '';
  }

  void _validatePasswordTwo(String password) {
    // 定义正则表达式，要求密码同时包含数字、字母及特殊字符，且长度至少为8个字符
    RegExp regex = RegExp(r'^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,18}$');

    // 使用正则表达式进行匹配
    if (!regex.hasMatch(password)) {
      // 如果密码不符合规则，返回一个错误消息

      pwdErrorTwo.value = '登录密码8-18位数，包含字母和数字，不支持特殊字符';
      return;
    }

    pwdErrorTwo.value = '';
  }

  void checkModiy() {
    enbled(
      pwd != null && pwd!.isNotEmpty && codes != null && codes!.isNotEmpty,
    );
  }

  void checkExchange() {
    changeExchangePswEnbled(
      pwd != null && pwd!.isNotEmpty && codes != null && codes!.isNotEmpty,
    );
  }

  //交易密码
  void changeExchangeValue(dynamic value, String type) {
    if (type == 'exchangePwd') {
      pwd = value;
    }
    if (type == 'againPwd') {
      againPwd = value;
    }
    if (type == 'smsId') {
      smsId = value;
    }
    if (type == 'codes') {
      codes = value;
    }
    // checkExchange();
  }

  void quitLogin() {
    http.netFetch<dynamic>(
      ApiUrl.logout,
      method: Method.post,
      params: {},
      success: (r) {
        HiCache.getInstance().remove(LoginController.boardingPassToken);

        Get.offAllNamed(LoginPage.path);
      },
    );
  }

  void updateAvatarImg(Function success) async {
    http.netFetch<dynamic>(
      ApiUrl.updateUserInfo,
      method: Method.post,
      params: {'avatarImg': avatarImg.value},
      success: (r) {
        success();
        // getUserInfo();
        globalController.getUserInfo();
      },
    );
  }

  //获取上传图片链接
  Future<String> getUploadUrl1() async {
    int timestampInSeconds = DateTime.now().millisecondsSinceEpoch ~/ 1000;
    try {
      final response = await http.netFetch<dynamic>(
        ApiUrl.getUploadUrl,
        method: Method.post,
        params: {'key': '$timestampInSeconds.png'},
      );

      if (response?.code == 200) {
        avatarImg.value = response?.data.split('?')[0];
        debugPrint('渠道图片地址: ${avatarImg.value}');
        return response?.data;
      }
      return response?.data;
    } catch (e) {
      debugPrint('获取上传地址出错: ${e.toString()}');
      rethrow; // 重新抛出异常，让外层处理
    }
  }

  void updateNickName(String nickName) async {
    if (nickName.isEmpty) {
      showToast('昵称不能为空');
      return;
    } else if (nickName.length > 15) {
      showToast('昵称不能超过15个字符');
      return;
    } else if (!RegExp(r'^[a-zA-Z0-9\u4e00-\u9fa5]+$').hasMatch(nickName)) {
      showToast('昵称只能包含数字、字母和文字');
      return;
    }
    http.netFetch<dynamic>(
      ApiUrl.updateUserInfo,
      method: Method.post,
      params: {'nickName': nickName},
      success: (r) {
        showToast('昵称已修改');
        globalController.getUserInfo();
      },
    );
  }

  void canCancelAccount(context) {
    http.netFetch<dynamic>(
      CommonApi.canCancelAccount,
      method: Method.post,
      success: (r) {
        if (!r.data) {
          showConfirmDialog(
            context: Get.context!,
            message: '钱包内有余额未处理，无法注销',
            messages: [],
            fontSize: 16,
            actions: [ActionModel(width: 204, label: '已知晓', onPressed: () {})],
          );
        } else {
          Get.toNamed(SettingLogOff.path);
        }
      },
    );
  }
}
